<template>
  <div class="outer">
    <div class="todo-container">
      <!-- 头部 -->
      <TodoHeader @addList="addList" />
      <!-- 内容展示区域 -->
      <TodoMain :todoList="todoList" />
      <!-- 底部区域 -->
      <TodoFooter @removeAll="removeAll" :isCheckAll="isCheckAll" :todoListLength="todoListLength" @chenckedAll="chenckedAll" />
    </div>
  </div>
</template>

<script>
import TodoHeader from "@/compontens/TodoHeader";
import TodoMain from "@/compontens/TodoMain";
import TodoFooter from "@/compontens/TodoFooter";
import { watch } from 'vue';
export default {
  name: "App",
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      todoList: [
        {
          id: Math.random().toString(8).slice(2),
          title: "打豆豆",
          isChecked: false,
        },
        {
          id: Math.random().toString(8).slice(2),
          title: "吃饭饭",
          isChecked: true,
        },
        {
          id: Math.random().toString(8).slice(2),
          title: "睡觉觉",
          isChecked: false,
        },
      ],
    };
  },
  methods: {
    //添加功能
    addList(e) {
      const msg = e.target.value.trim();
      e.target.value = "";
      if (msg.length === 0) {
        alert("请输入内容");
        return;
      }
      const info = this.todoList.find((item) => item.title === msg);
      if (info) {
        alert("请不要输入重复内容");
        return;
      }
      this.todoList.unshift({
        id: Math.random().toString(8).slice(2),
        title: msg,
        isChecked: false,
      });
    },
    //单个删除功能
    removeById(id){
      this.todoList = this.todoList.filter(item => item.id !== id)
    },
    //改变todoList选中属性
    changeChecked(id){
      const index = this.todoList.findIndex(item => item.id === id)
      this.todoList[index].id = this.todoList[index]
    },
    //删除全部已选中
    removeAll(){
      this.todoList = this.todoList.filter(item => item.isChecked !== true)
    },
    //全选按钮
    chenckedAll(value){
      this.todoList = this.todoList.map(item => {
        item.isChecked = value;
        return item
      })
    }
  },
  computed:{
    isCheckAll(){
      return this.todoList.filter(item => item.isChecked === true).length
    },
    todoListLength(){
      return this.todoList.length
    }
  },
  mounted(){
    //事件总线
    this.$bus.$on("removeById",this.removeById)
    this.$bus.$on("changeChecked",this.changeChecked)
    this.todoList = JSON.parse(localStorage.todoList).length > 0 ? JSON.parse(localStorage.todoList) : []
  },
  //数据储存化
  watch:{
    todoList:{
      deep: true,
      handler(){
        localStorage.setItem("todoList",JSON.stringify(this.todoList))
      }
    }
  }
};
</script>

<style>
@import url("@/App.css");
</style>